﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Jy123.BLL.Public;
using Jy123.Model;

namespace Jy123.BLL.User
{
    public class Friend
    {
        /// <summary>
        /// 判断是否是好友
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <param name="friendid">好友ID</param>
        /// <returns>true/false</returns>
        public static bool IsFriends(int userid, int friendid)
        {
            string Sql = "select count(ID) from User_Friend where FUser=" + userid + " and FFriend=" + friendid;

            int n = (int)DBUtility.DbHelperSQL.ExecuteSql(Sql);
            if (n < 1)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 是否在同一网络中
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <param name="friendid">好友ID</param>
        /// <returns>true/false</returns>
        static internal bool IsInSameNetwork(int userid, int friendid)
        {
            string Sql = "select Province from User_Main where ID=" + userid;
            object obj1 = DBUtility.DbHelperSQL.ExecuteSql(Sql);
            Sql = "select Province from User_Main where ID=" + friendid;
            object obj2 = DBUtility.DbHelperSQL.ExecuteSql(Sql);
            if (obj1 != null && obj1 != DBNull.Value && obj1 == obj2)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 删除好友分类
        /// </summary>
        /// <param name="ID">分类ID</param>
        /// <param name="UserID">用户ID</param>
        public void DelFriendClass(int ID, int UserID)
        {
            string sql = "delete User_FriendClass where ID=" + ID + " and FUser=" + UserID;
            DBUtility.DbHelperSQL.ExecuteSql(sql);
            string sql1 = "update User_Friend set FFriendClass=0 where FFriendClass=" + ID;
            DBUtility.DbHelperSQL.ExecuteSql(sql1);
        }
        /// <summary>
        /// 得到好友分类列表
        /// </summary>
        /// <param name="UserID">用户的ID</param>
        /// <returns>分类信息数据集</returns>
        public DataSet GetFriendClass(int UserID)
        {
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@UserID", SqlDbType.Int);
            param[0].Value = UserID;
            int rowsAffect = 0;
            return DBUtility.DbHelperSQL.RunProcedure("SP_User_FriendClass", param, rowsAffect);
            //return DBUtility.DbHelperSQL.ExecuteReader("SP_User_FriendClass", param);
        }
        public List<Model.User_Main> GetAllFriends(int userId)
        {
            User_Main BLLUser = new User_Main();
            string strWhere = string.Format("ID IN (SELECT FFriend FROM User_Friend WHERE FUser = {0})", userId.ToString());
            List<Model.User_Main> list = BLLUser.GetModelList(strWhere);
            return list;
        }
        /// <summary>
        /// 获得好友列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet GetFriendList(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "FUser = '" + userid + "'and state =1",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendList"
            }, out counts);
        }
        /// <summary>
        /// 获得好友列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="friendClass">好友分类的ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet GetFriendList(int cpage, int psize, int userid, int friendClass, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "FUser = '" + userid + "'and state =1 and FFriendClass='" + friendClass + "'",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendList"
            }, out counts);
        }

        /// <summary>
        /// 获得好友列表(按地区)
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="provinceID">地区ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet GetFriendListByProvince(int cpage, int psize, int userid, int provinceID, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "FUser = '" + userid + "'and state =1 and Province='" + provinceID + "'",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendList"
            }, out counts);
        }
        /// <summary>
        /// 根据地区好友分类的列表
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>数据集</returns>
        public DataSet FriendInAreaList(int userID)
        {
            SqlParameter[] parameter = { 
                                       new SqlParameter("@UserID",SqlDbType.Int)};
            parameter[0].Value = userID;
            int rowsAffect = 0;
            return DBUtility.DbHelperSQL.RunProcedure("SP_User_FriendAreaClass", parameter, rowsAffect);
        }
        /// <summary>
        /// 查询可能认识的好友列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet FriendCongnition(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "(State=5 or State=2) and ID in (select Ffriend from [User_Friend] where FUser in(select FFriend from [User_Friend] where FUser='" + userid + "'))and ID not in(select FFriend from [User_Friend] where FUser='" + userid + "')and ID!='" + userid + "'",
                //Filter = "(State=5 or State=2) and ID not in(select FFriend from [User_Friend] where FUser='" + userid + "'and state =1)and ID!='" + userid + "'",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendCognition",
                //Sort="NID asc"
                Sort = "ID asc"
            }, out counts);
        }
        /// <summary>
        /// 随便看看的好友列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet FriendRandom(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                //Filter = "(State=5 or State=2) and ID in (select ID	from [User_Friend] where FUser in(select FFriend from [User_Friend] where FUser='" + userid + "'))and ID not in(select FFriend from [User_Friend] where FUser='" + userid + "')and ID!='" + userid + "'",
                Filter = "(State=5 or State=2) and ID not in(select FFriend from [User_Friend] where FUser='" + userid + "'and state =1)and ID!='" + userid + "'",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendCognition",
                Sort = "NID asc"
            }, out counts);
        }
        /// <summary>
        /// 搜索陌生人
        /// </summary>
        /// <param name="cpage">起始页</param>
        /// <param name="psize">页大小</param>
        /// <param name="userName">要搜索的名字</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet SearchUserByUserName(int cpage, int psize, string userName, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                //Filter = "(State=5 or State=2) and ID in (select ID	from [User_Friend] where FUser in(select FFriend from [User_Friend] where FUser='" + userid + "'))and ID not in(select FFriend from [User_Friend] where FUser='" + userid + "')and ID!='" + userid + "'",
                Filter = "UserName like '%" + userName + "%'",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendCognition",
                Sort = "NID asc"
            }, out counts);
        }
        /// <summary>
        /// 查询在线的好友列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet FriendOnline(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "FUser = '" + userid + "'and datediff(mi,lastlogintime,getdate())<30",//登陆30分钟之内的好友/mi为分钟，ss为秒，hh为小时
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendOnlineList",
                Sort = "LastLoginTime desc"
            }, out counts);
        }

        /// <summary>
        /// 我去看过谁列表
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet FriendGetVisitList_Out(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "(FUserVisitor = '" + userid + "')",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendGetVisitList_Out",
                Sort = "LastVisitTime DESC"
            }, out counts);
        }

        /// <summary>
        /// 谁来看过我
        /// </summary>
        /// <param name="cpage">当前页</param>
        /// <param name="psize">需要获取的数量</param>
        /// <param name="userid">用户ID</param>
        /// <param name="counts">总数[0],页数[1]</param>
        /// <returns>数据集</returns>
        public DataSet FriendGetVisitList_In(int cpage, int psize, int userid, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "(FUser = '" + userid + "')",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendGetVisitList_In",
                Sort = "LastVisitTime DESC"
            }, out counts);
        }
        /// <summary>
        /// 根据好友名字搜索好友
        /// </summary>
        /// <param name="cpage"></param>
        /// <param name="psize"></param>
        /// <param name="userid"></param>
        /// <param name="friendName"></param>
        /// <param name="counts"></param>
        /// <returns></returns>
        public DataSet SearchFriend(int cpage, int psize, int userid, string friendName, out List<int?> counts)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "(FUser = '" + userid + "' and UserName Like '%" + friendName + "%')",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_FriendList",
                Sort = "AddTime DESC"
            }, out counts);
        }
        /// <summary>
        /// 根据用户Email查找ID
        /// </summary>
        /// <param name="email">Email</param>
        /// <returns>USERID</returns>
        public int SearchUserIDbyEmail(string email)
        {
            string strSql = "SELECT ID FROM User_Main WHERE (Email = @Email)";
            SqlParameter[] parameter ={
                                      new SqlParameter("@Email",SqlDbType.VarChar)};
            parameter[0].Value = email;
            int result = 0;
            object sqlResult = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            if (sqlResult != null)
            {
                return (int)sqlResult;
            }
            return result;
        }
        /// <summary>
        /// 统计用户的好友请求数量
        /// </summary>
        /// <param name="userID">当前用户的ID</param>
        /// <returns>请求数量</returns>
        public int CountRequest(int userID)
        {
            string strSql = "select count(*) from dbo.User_Friend where FFriend =@UserID  and State= 0";
            SqlParameter[] parameter ={
                                      new SqlParameter("@UserID",SqlDbType.Int)};
            parameter[0].Value = userID;
            int result = 0;
            object sqlResult = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            if (sqlResult != null)
            {
                return (int)sqlResult;
            }
            return result;
        }

        /// <summary>
        /// 判断是否已发送过请求(0为已发送请求等待确认，1为已确认的好友，2为拒绝or未发送请求)
        /// </summary>
        /// <param name="demanderID">请求者ID</param>
        /// <param name="receiverID">被请求者ID</param>
        /// <returns>是否已发送过请求</returns>
        public int AlreadySearch(int demanderID, int receiverID)
        {
            //string strSql = "select ReplyResult from dbo.User_Request where FUserDemander=@FUserDemander and FUserReceiver=@FUserReceiver";
            // "select ReplyResult from dbo.User_Request where (FUserDemander=@FUserDemander and FUserReceiver=@FUserReceiver)or(FUserReceiver=@FUserDemander and FUserDemander=@FUserReceiver)";

            string strSql = "select State from User_Friend where (FUser=@FUserDemander and FFriend=@FUserReceiver)or(FFriend=@FUserDemander and FUser=@FUserReceiver)";
            SqlParameter[] parameter ={
                                      new SqlParameter("@FUserDemander",SqlDbType.Int),
                                      new SqlParameter("@FUserReceiver",SqlDbType.Int)};
            parameter[0].Value = demanderID;
            parameter[1].Value = receiverID;
            object isRequested = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            int type = 2;
            try
            {
                if (isRequested != null)
                {
                    type = Convert.ToInt32(isRequested);
                }

            }
            catch
            {
                type = 2;
            }

            return type;
        }
        /// <summary>
        /// 好友请求列表
        /// </summary>
        /// <param name="cpage">起始页</param>
        /// <param name="psize">页记录大小</param>
        /// <param name="userid">被请求的用户ID</param>
        /// <returns>数据集</returns>
        public DataSet FriendRequest(int cpage, int psize, int userid)
        {
            return Pagination.GetList(new MPagination()
            {
                Filter = "FFriend = '" + userid + "'and State =0",
                CurrentPage = cpage,
                Fields = "*",
                PageSize = psize,
                PrimaryKey = "ID",
                Tables = "V_User_Friend_RequestList"
            });
        }

        /// <summary>
        /// 统计用户的好友请求数量
        /// </summary>
        /// <param name="fUserReceiverID">被统计用户的ID</param>
        /// <returns>未处理的请求数量</returns>
        public int CountFriendRequest(int fUserReceiverID)
        {
            string strSql = "select count(ID) from dbo.User_Friend where FFriend = @FUserReceiverID and state =0";
            SqlParameter[] parameter ={
                                      new SqlParameter("@FUserReceiverID",SqlDbType.Int)};
            parameter[0].Value = fUserReceiverID;
            int result = 0;
            object sqlResult = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            if (sqlResult != null)
            {
                return (int)sqlResult;
            }
            return result;
        }
        /// <summary>
        /// 解除好友关系
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="friendID">好友ID</param>
        /// <returns>0为解除失败、大于0为解除成功</returns>
        public int delFriend(int userID, int friendID)
        {
            //string strSql = "select ReplyResult from dbo.User_Request where FUserDemander=@FUserDemander and FUserReceiver=@FUserReceiver";
            // "select ReplyResult from dbo.User_Request where (FUserDemander=@FUserDemander and FUserReceiver=@FUserReceiver)or(FUserReceiver=@FUserDemander and FUserDemander=@FUserReceiver)";

            string strSql = "delete User_Friend where (FUser=@FUser and FFriend=@FUserFriend)or(FFriend=@FUser and FUser=@FUserFriend)";
            SqlParameter[] parameter ={
                                      new SqlParameter("@FUser",SqlDbType.Int),
                                      new SqlParameter("@FUserFriend",SqlDbType.Int)};
            parameter[0].Value = userID;
            parameter[1].Value = friendID;

            int effectRows = 0;
            effectRows = DBUtility.DbHelperSQL.ExecuteSql(strSql, parameter);
            return effectRows;
        }


        /// <summary>
        /// 统计空分类的好友数量
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>好友数量</returns>
        public int CountFrdClassNull(int userID)
        {
            //string strSql = "select count(*) from dbo.User_Friend where FFriend =@UserID  and State= 0";
            string strSql = "select count(id) from dbo.User_Friend where fuser=@UserID and State= 1 and ffriendclass=0";
            SqlParameter[] parameter ={
                                      new SqlParameter("@UserID",SqlDbType.Int)};
            parameter[0].Value = userID;
            int result = 0;
            object sqlResult = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            if (sqlResult != null)
            {
                return (int)sqlResult;
            }
            return result;
        }
        /// <summary>
        /// 统计未知地区的好友数量
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>好友数量</returns>
        public int CountFrdAreaNull(int userID)
        {
            //string strSql = "select count(*) from dbo.User_Friend where FFriend =@UserID  and State= 0";
            string strSql = "select count(id) from dbo.V_User_FriendList where fuser=@UserID and State= 1 and Province=0";
            SqlParameter[] parameter ={
                                      new SqlParameter("@UserID",SqlDbType.Int)};
            parameter[0].Value = userID;
            int result = 0;
            object sqlResult = DBUtility.DbHelperSQL.GetSingle(strSql, parameter);
            if (sqlResult != null)
            {
                return (int)sqlResult;
            }
            return result;
        }

        /// <summary>
        /// 删除用户的同时删除与该用户相关的好友关系
        /// </summary>
        /// <param name="fUserID">被执行的用户ID</param>
        /// <returns>0为解除失败、大于0为解除成功</returns>
        public int delFriendByDelUser(int fUserID)
        {
            string strSql = "delete User_Friend where (fuser=@FUser or ffriend=@FUser)";
            SqlParameter[] parameter ={
                                      new SqlParameter("@FUser",SqlDbType.Int)};
            parameter[0].Value = fUserID;

            int effectRows = 0;
            effectRows = DBUtility.DbHelperSQL.ExecuteSql(strSql, parameter);
            return effectRows;
        }
    }
}
